/**
 * Virtual DOM patching algorithm based on Snabbdom by
 * Simon Friis Vindum (@paldepind)
 * Licensed under the MIT License
 * https://github.com/paldepind/snabbdom/blob/master/LICENSE
 *
 * modified by Evan You (@yyx990803)
 *
 * Not type-checking this because this file is perf-critical and the cost
 * of making flow understand it is not worth it.
 */

import VNode, { cloneVNode } from './vnode'
import config from '../config'
import { SSR_ATTR } from 'shared/constants'
import { registerRef } from './modules/ref'
import { traverse } from '../observer/traverse'
import { activeInstance } from '../instance/lifecycle'
import { isTextInputType } from 'web/util/element'

import {
  warn,
  isDef,
  isUndef,
  isTrue,
  makeMap,
  isRegExp,
  isPrimitive
} from '../util/index'

export const emptyNode = new VNode('', {}, [])

const hooks = ['create', 'activate', 'update', 'remove', 'destroy']

function sameVnode(a, b) {
  return (
    a.key === b.key && (
      (
        a.tag === b.tag &&
        a.isComment === b.isComment &&
        isDef(a.data) === isDef(b.data) &&
        sameInputType(a, b)
      ) || (
        isTrue(a.isAsyncPlaceholder) &&
        a.asyncFactory === b.asyncFactory &&
        isUndef(b.asyncFactory.error)
      )
    )
  )
}

function sameInputType(a, b) {
  if (a.tag !== 'input') return true
  let i
  const typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type
  const typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type
  return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)
}

function createKeyToOldIdx(children, beginIdx, endIdx) {
  let i, key
  const map = {}
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key
    if (isDef(key)) map[key] = i
  }
  return map
}


export function createPatchFunction(backend) {
  let i, j
  const cbs = {}
  //nodeOps的方法在platforms/web/runtime/node-ops/js
  const { modules, nodeOps } = backend

  for (i = 0; i < hooks.length; ++i) {
    cbs[hooks[i]] = []
    for (j = 0; j < modules.length; ++j) {
      if (isDef(modules[j][hooks[i]])) {
        cbs[hooks[i]].push(modules[j][hooks[i]])
      }
    }
  }

  function emptyNodeAt(elm) {
    return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
  }

  function createRmCb(childElm, listeners) {
    function remove() {
      if (--remove.listeners === 0) {
        removeNode(childElm)
      }
    }
    remove.listeners = listeners
    return remove
  }

  function removeNode(el) {
    const parent = nodeOps.parentNode(el)
    // element may have already been removed due to v-html / v-text
    if (isDef(parent)) {
      nodeOps.removeChild(parent, el)
    }
  }

  function isUnknownElement(vnode, inVPre) {
    return (
      !inVPre &&
      !vnode.ns &&
      !(
        config.ignoredElements.length &&
        config.ignoredElements.some(ignore => {
          return isRegExp(ignore)
            ? ignore.test(vnode.tag)
            : ignore === vnode.tag
        })
      ) &&
      config.isUnknownElement(vnode.tag)
    )
  }




  /**
   * 传递一个树状结构的vnode， 当前方法会递归生成真实的Dom，然后保存在vnode.elm属性里面
   * @param {*} vnode 虚拟vnode
   * @param {*} insertedVnodeQueue  一个数组，在递归时会一直传递下去给子类，未知作用
   * @param {*} parentElm 父节点，用于确定关系，比如当前是文本节点，那么解析完就插入到父节点里面，根节点的父节点是body
   * @param {*} refElm  引用Dom，在首次使用当前方法时会传递，其它子类不会,用于标记当前Dom是不是root元素了，用于insert()方法的判断
   * @param {*} nested 标记是不是根Dom, 如果是根这里不传，其它的都是true
   * @param {*} ownerArray 所有子类，比如当前Dom有父级，那么这里就保存了当前父级所有的子类Dom
   * @param {*} index 索引，当前是父级的第几个子类
   */
  function createElm(
    vnode,
    insertedVnodeQueue,
    parentElm,
    refElm,
    nested,
    ownerArray,
    index
  ) {
    if (isDef(vnode.elm) && isDef(ownerArray)) {
      //这个vnode在之前的渲染中使用过!
      //现在它被用作一个新节点，重写它的elm将导致
      //当它被用作插入时可能会出现补丁错误
      //引用节点。相反，我们在创建之前按需克隆节点
      //为它关联的DOM元素。
      vnode = ownerArray[index] = cloneVNode(vnode)
    }

    vnode.isRootInsert = !nested // for transition enter check 过度输入检查，这里是true
    //如果当前vNode是组件，那么会走次路线
    if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
      return
    }

    //元素的所有attr属性
    const data = vnode.data
    const children = vnode.children
    const tag = vnode.tag

    // 当元素的不空文本字符串时会走当前if分钟，然后一直递归，直到文本节点, 走else分支
    if (isDef(tag)) {

      //单纯的给vnode添加elm属性，值是一个div元素
      vnode.elm = vnode.ns
        ? nodeOps.createElementNS(vnode.ns, tag)
        : nodeOps.createElement(tag, vnode)
      // 首次渲染啥也没干
      setScope(vnode)

      /* istanbul ignore if */
      if (__WEEX__) {
        // in Weex, the default insertion order is parent-first.
        // List items can be optimized to use children-first insertion
        // with append="tree".
        const appendAsTree = isDef(data) && isTrue(data.appendAsTree)
        if (!appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
        createChildren(vnode, children, insertedVnodeQueue)
        if (appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
      } else {

        //这部是关键，因为vNode是树状结构的，createChildren方法实际也是循环children然后递归调用
        //当前方法createElm， 传递Dom元素
        createChildren(vnode, children, insertedVnodeQueue)
        if (isDef(data)) {
          // insertedVnodeQueue数里里面存储着初始化完成的组件
          invokeCreateHooks(vnode, insertedVnodeQueue)
        }
        //把当前Dom节点插入到父级
        insert(parentElm, vnode.elm, refElm)
      }

    } else if (isTrue(vnode.isComment)) { //判断当前vNode是不是component
      vnode.elm = nodeOps.createComment(vnode.text)
      insert(parentElm, vnode.elm, refElm)
    } else {  //最终结果判断是文本节点
      //创建空文本节点
      vnode.elm = nodeOps.createTextNode(vnode.text)
      //把当前文本节点插入到父节点
      insert(parentElm, vnode.elm, refElm)
    }
  }

  function createComponent(vnode, insertedVnodeQueue, parentElm, refElm) {
    let i = vnode.data
    if (isDef(i)) {
      //被keep-alive缓存的组件才会有keepAlive= true的属性
      const isReactivated = isDef(vnode.componentInstance) && i.keepAlive
      if (isDef(i = i.hook) && isDef(i = i.init)) {
        //这个if条件有点骚气，其实就是获取到i里面的hook属性的init方法不为空，然后赋值给i
        //那这个init方法怎么来的呢？它在./create-component.js/createComponent函数里面赋值来的
        //如果是内置标签那么在createElm方法里面直接就调用new Vnode就完成了，如果是组件它会调用createComponent方法来生成组件的new Vnode
        //这里开始进入子组件的$mount环节， i方法执行完成后，其实就代码了一个组件已经解析完成，解析好真实Dom在组件实例的$el上
        i(vnode, false /* hydrating */)
      }

      //这里已经解析完一个组件，但是并不知道当前组件是插入到父类的那个未知
      if (isDef(vnode.componentInstance)) {
        //组件的一些属性class,style,事件全部初始化完成，
        initComponent(vnode, insertedVnodeQueue)
        //插入父级
        insert(parentElm, vnode.elm, refElm)
        if (isTrue(isReactivated)) {
          reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm)
        }
        return true
      }
    }
  }

  function initComponent(vnode, insertedVnodeQueue) {
    if (isDef(vnode.data.pendingInsert)) {
      //将两个数组合并
      //如果是最底层组件，insertedVnodeQueue是空
      insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
      vnode.data.pendingInsert = null
    }
    //设置真实元素
    vnode.elm = vnode.componentInstance.$el
    //这个if条件很奇怪，如果是组件就会成立，非组件不会成立
    if (isPatchable(vnode)) {
      invokeCreateHooks(vnode, insertedVnodeQueue)
      setScope(vnode)
    } else {
      // empty component root.
      // skip all element-related modules except for ref (#3455)
      registerRef(vnode)
      // make sure to invoke the insert hook
      insertedVnodeQueue.push(vnode)
    }
  }

  function reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) {
    let i
    // hack for #4339: a reactivated component with inner transition
    // does not trigger because the inner node's created hooks are not called
    // again. It's not ideal to involve module-specific logic in here but
    // there doesn't seem to be a better way to do it.
    let innerNode = vnode
    while (innerNode.componentInstance) {
      innerNode = innerNode.componentInstance._vnode
      if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
        for (i = 0; i < cbs.activate.length; ++i) {
          cbs.activate[i](emptyNode, innerNode)
        }
        insertedVnodeQueue.push(innerNode)
        break
      }
    }
    // unlike a newly created component,
    // a reactivated keep-alive component doesn't insert itself
    insert(parentElm, vnode.elm, refElm)
  }

  //插入节点，传入的elm是root节点时会进入if分支，其它都是else
  function insert(parent, elm, ref) {
    if (isDef(parent)) {
      if (isDef(ref)) {
        if (nodeOps.parentNode(ref) === parent) {
          nodeOps.insertBefore(parent, elm, ref)
        }
      } else {
        nodeOps.appendChild(parent, elm)
      }
    }
  }

  function createChildren(vnode, children, insertedVnodeQueue) {
    if (Array.isArray(children)) {
      if (process.env.NODE_ENV !== 'production') {
        // 检查v-for的key属性
        checkDuplicateKeys(children)
      }
      for (let i = 0; i < children.length; ++i) {
        createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i)
      }
    } else if (isPrimitive(vnode.text)) {
      nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
    }
  }

  function isPatchable(vnode) {
    while (vnode.componentInstance) {
      vnode = vnode.componentInstance._vnode
    }
    return isDef(vnode.tag)
  }

  /**
   * 解析组件的属性
   * @param {} vnode 
   * @param {*} insertedVnodeQueue 
   */
  function invokeCreateHooks(vnode, insertedVnodeQueue) {
    //组件解析好了，但是还没有解析属性，cbs里面有很多解析属性的函数，这里逐一调用
    //create数组里面的函数有
    // updateAttrs, updateClass, updateDOMListeners, updateDOMProps, updateStyle,
    // _enter, _create, create, updateDirectives
    for (let i = 0; i < cbs.create.length; ++i) {
      cbs.create[i](emptyNode, vnode)
    }
    //这里得到的i就是./create-component.js/componentVNodeHooks里面的属性，只有组件才会有此属性
    i = vnode.data.hook
    if (isDef(i)) {
      if (isDef(i.create)) i.create(emptyNode, vnode)
      //这里条件为真，把当前vnode添加到插入队列
      if (isDef(i.insert)) insertedVnodeQueue.push(vnode)
    }
  }

  // set scope id attribute for scoped CSS.
  // this is implemented as a special case to avoid the overhead
  // of going through the normal attribute patching process.
  function setScope(vnode) {
    let i
    if (isDef(i = vnode.fnScopeId)) {
      nodeOps.setStyleScope(vnode.elm, i)
    } else {
      let ancestor = vnode
      while (ancestor) {
        if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
          nodeOps.setStyleScope(vnode.elm, i)
        }
        ancestor = ancestor.parent
      }
    }
    // for slot content they should also get the scopeId from the host instance.
    if (isDef(i = activeInstance) &&
      i !== vnode.context &&
      i !== vnode.fnContext &&
      isDef(i = i.$options._scopeId)
    ) {
      nodeOps.setStyleScope(vnode.elm, i)
    }
  }

  function addVnodes(parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
    for (; startIdx <= endIdx; ++startIdx) {
      createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx)
    }
  }

  function invokeDestroyHook(vnode) {
    let i, j
    const data = vnode.data
    if (isDef(data)) {
      if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
      for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
    }
    if (isDef(i = vnode.children)) {
      for (j = 0; j < vnode.children.length; ++j) {
        invokeDestroyHook(vnode.children[j])
      }
    }
  }

  function removeVnodes(vnodes, startIdx, endIdx) {
    for (; startIdx <= endIdx; ++startIdx) {
      const ch = vnodes[startIdx]
      if (isDef(ch)) {
        if (isDef(ch.tag)) {
          removeAndInvokeRemoveHook(ch)
          invokeDestroyHook(ch)
        } else { // Text node
          removeNode(ch.elm)
        }
      }
    }
  }

  function removeAndInvokeRemoveHook(vnode, rm) {
    if (isDef(rm) || isDef(vnode.data)) {
      let i
      const listeners = cbs.remove.length + 1
      if (isDef(rm)) {
        // we have a recursively passed down rm callback
        // increase the listeners count
        rm.listeners += listeners
      } else {
        // directly removing
        rm = createRmCb(vnode.elm, listeners)
      }
      // recursively invoke hooks on child component root node
      if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
        removeAndInvokeRemoveHook(i, rm)
      }
      for (i = 0; i < cbs.remove.length; ++i) {
        cbs.remove[i](vnode, rm)
      }
      if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
        i(vnode, rm)
      } else {
        rm()
      }
    } else {
      removeNode(vnode.elm)
    }
  }

  //比较子类: 双端比较算法
  function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
    //旧节点开始索引
    let oldStartIdx = 0
    //新节点开始索引
    let newStartIdx = 0
    //旧节点末尾索引
    let oldEndIdx = oldCh.length - 1
    //新节点末尾索引
    let newEndIdx = newCh.length - 1
    //第一个旧节点
    let oldStartVnode = oldCh[0]
    //最后一个旧节点
    let oldEndVnode = oldCh[oldEndIdx]
    //第一个新节点
    let newStartVnode = newCh[0]
    //最后一个新节点
    let newEndVnode = newCh[newEndIdx]
    let oldKeyToIdx, idxInOld, vnodeToMove, refElm

    // removeOnly是一个特殊的标志，仅由使用
    //确保被移除的元素保持在正确的相对位置
    //在离开过渡期间
    const canMove = !removeOnly

    // 检查子类的key是否重复
    // if (process.env.NODE_ENV !== 'production') {
    //   checkDuplicateKeys(newCh)
    // }
    /**
     * 双端比较算法
     * 概述：
     *    新旧两个数组，开头和结束比较，比较后然后就索引向中间移动一位，一直到中间位数则比较结束
     * 情况一：
     *    新旧两个数组只有顺序变化
     * 情况二：
     * 
     */
    while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
      if (isUndef(oldStartVnode)) {
        oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
      } else if (isUndef(oldEndVnode)) {
        oldEndVnode = oldCh[--oldEndIdx]
      } else if (sameVnode(oldStartVnode, newStartVnode)) { //1.开始与开始
        patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
        oldStartVnode = oldCh[++oldStartIdx]
        newStartVnode = newCh[++newStartIdx]
      } else if (sameVnode(oldEndVnode, newEndVnode)) { //2.结束与结束
        patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
        oldEndVnode = oldCh[--oldEndIdx]
        newEndVnode = newCh[--newEndIdx]
      } else if (sameVnode(oldStartVnode, newEndVnode)) { //3.开始与结束
        patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
        canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
        oldStartVnode = oldCh[++oldStartIdx]
        newEndVnode = newCh[--newEndIdx]
      } else if (sameVnode(oldEndVnode, newStartVnode)) { //4.结束与开始
        patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
        canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
        oldEndVnode = oldCh[--oldEndIdx]
        newStartVnode = newCh[++newStartIdx]
      } else {
     

        /**
         * 返回oldStartIdx到oldEndIdx之间oldCh的元素的key，用一个对象保存
         * key就是oldCh元素的key,值就是索引
         */
        if (isUndef(oldKeyToIdx)){
          oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
        }

        /**
         * 5. findIdxInOld：从旧数组中找到和新数组第一个元素相等的元素，返回索引
         *    索引存在说明旧数组元素移动到新数组的首位了
         *    索引不存在，说明当前是新数组的首位元素是新增元素
         */
        idxInOld = isDef(newStartVnode.key)
          ? oldKeyToIdx[newStartVnode.key]
          : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
        if (isUndef(idxInOld)) { 
          //新数组第一个新元素找不到在旧数组的位置，说明是新元素
          createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
        } else {
          //新数组第一个元素在旧数组中找到了位置，进行元素的位置替换
         
          vnodeToMove = oldCh[idxInOld] //找到旧数组中和新数组第一位相同的元素
          //两者完全相同
          if (sameVnode(vnodeToMove, newStartVnode)) {
            patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
            //把旧数组中对应的旧元素删除掉
            oldCh[idxInOld] = undefined
            //真实元素替换
            canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)
          } else {
            // 两者只是key相同而已
            // same key but different element. treat as new element
            createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
          }
        }
        
        newStartVnode = newCh[++newStartIdx]
      }
    }

    if (oldStartIdx > oldEndIdx) {
      refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
      addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
    } else if (newStartIdx > newEndIdx) {
      removeVnodes(oldCh, oldStartIdx, oldEndIdx)
    }
  }

  function checkDuplicateKeys(children) {
    const seenKeys = {}
    for (let i = 0; i < children.length; i++) {
      const vnode = children[i]
      const key = vnode.key
      if (isDef(key)) {
        if (seenKeys[key]) {
          warn(
            `Duplicate keys detected: '${key}'. This may cause an update error.`,
            vnode.context
          )
        } else {
          seenKeys[key] = true
        }
      }
    }
  }

  function findIdxInOld(node, oldCh, start, end) {
    for (let i = start; i < end; i++) {
      const c = oldCh[i]
      if (isDef(c) && sameVnode(node, c)) return i
    }
  }

  /**
   * 
   * @param {*} oldVnode //旧vnode
   * @param {*} vnode  //新vnode
   * @param {*} insertedVnodeQueue  //插入数组
   * @param {*} ownerArray //当前新vnode属于的父级数组
   * @param {*} index  //当前新vnode属于父级数组第几个元素
   * @param {*} removeOnly 
   */
  function patchVnode(
    oldVnode,
    vnode,
    insertedVnodeQueue,
    ownerArray,
    index,
    removeOnly
  ) {
    if (oldVnode === vnode) {
      return
    }

    if (isDef(vnode.elm) && isDef(ownerArray)) {
      // clone reused vnode
      vnode = ownerArray[index] = cloneVNode(vnode)
    }

    const elm = vnode.elm = oldVnode.elm

    //ssr相关的
    if (isTrue(oldVnode.isAsyncPlaceholder)) {
      if (isDef(vnode.asyncFactory.resolved)) {
        hydrate(oldVnode.elm, vnode, insertedVnodeQueue)
      } else {
        vnode.isAsyncPlaceholder = true
      }
      return
    }

    // reset by the hot-reload-api and we need to do a proper re-render.
    //为静态树重用元素。
    //注意:我们只在vnode被克隆的时候才这么做
    //如果新节点没有被克隆，它意味着渲染函数已经被克隆
    //通过hot-reload-api重置，我们需要做一个适当的重新渲染。
    if (isTrue(vnode.isStatic) &&
      isTrue(oldVnode.isStatic) &&
      vnode.key === oldVnode.key &&
      (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
    ) {
      vnode.componentInstance = oldVnode.componentInstance
      return
    }

    let i
    const data = vnode.data
    //更新props,listence,插槽
    if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
      i(oldVnode, vnode)
    }

    const oldCh = oldVnode.children
    const ch = vnode.children

    if (isDef(data) && isPatchable(vnode)) {
      //更新vnode的属性,包括如下：
      //当前的方法在platforms/web/runtime/modules目录下
      // updateAttrs(oldVnode, vnode)
      // updateClass(oldVnode, vnode)
      // updateDOMListeners(oldVnode, vnode)
      // updateDOMProps(oldVnode, vnode)
      // updateStyle(oldVnode, vnode)
      // update(oldVnode, vnode)
      // updateDirectives(oldVnode, vnode)
      for (i = 0; i < cbs.update.length; ++i){
        cbs.update[i](oldVnode, vnode)
      }
      if (isDef(i = data.hook) && isDef(i = i.update)){
        i(oldVnode, vnode)
      }
    }


    if (isUndef(vnode.text)) {
      if (isDef(oldCh) && isDef(ch)) {
        //进入子类diff阶段
        if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
      } else if (isDef(ch)) {
        //检查子类相同的key
        if (process.env.NODE_ENV !== 'production') {
          checkDuplicateKeys(ch)
        }
        if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
        addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
      } else if (isDef(oldCh)) {
        removeVnodes(oldCh, 0, oldCh.length - 1)
      } else if (isDef(oldVnode.text)) {
        nodeOps.setTextContent(elm, '')
      }
    } else if (oldVnode.text !== vnode.text) {
      nodeOps.setTextContent(elm, vnode.text)
    }
    if (isDef(data)) {
      if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
    }
  }

  function invokeInsertHook(vnode, queue, initial) {
    // delay insert hooks for component root nodes, invoke them after the
    // element is really inserted
    if (isTrue(initial) && isDef(vnode.parent)) {
      vnode.parent.data.pendingInsert = queue
    } else {
      for (let i = 0; i < queue.length; ++i) {
        queue[i].data.hook.insert(queue[i])
      }
    }
  }

  let hydrationBailed = false
  // list of modules that can skip create hook during hydration because they
  // are already rendered on the client or has no need for initialization
  // Note: style is excluded because it relies on initial clone for future
  // deep updates (#7063).
  const isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key')

  // Note: this is a browser-only function so we can assume elms are DOM nodes.
  function hydrate(elm, vnode, insertedVnodeQueue, inVPre) {
    let i
    const { tag, data, children } = vnode
    inVPre = inVPre || (data && data.pre)
    vnode.elm = elm

    if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {
      vnode.isAsyncPlaceholder = true
      return true
    }
    // assert node match
    if (process.env.NODE_ENV !== 'production') {
      if (!assertNodeMatch(elm, vnode, inVPre)) {
        return false
      }
    }
    if (isDef(data)) {
      if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
      if (isDef(i = vnode.componentInstance)) {
        // child component. it should have hydrated its own tree.
        initComponent(vnode, insertedVnodeQueue)
        return true
      }
    }
    if (isDef(tag)) {
      if (isDef(children)) {
        // empty element, allow client to pick up and populate children
        if (!elm.hasChildNodes()) {
          createChildren(vnode, children, insertedVnodeQueue)
        } else {
          // v-html and domProps: innerHTML
          if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {
            if (i !== elm.innerHTML) {
              /* istanbul ignore if */
              if (process.env.NODE_ENV !== 'production' &&
                typeof console !== 'undefined' &&
                !hydrationBailed
              ) {
                hydrationBailed = true
                console.warn('Parent: ', elm)
                console.warn('server innerHTML: ', i)
                console.warn('client innerHTML: ', elm.innerHTML)
              }
              return false
            }
          } else {
            // iterate and compare children lists
            let childrenMatch = true
            let childNode = elm.firstChild
            for (let i = 0; i < children.length; i++) {
              if (!childNode || !hydrate(childNode, children[i], insertedVnodeQueue, inVPre)) {
                childrenMatch = false
                break
              }
              childNode = childNode.nextSibling
            }
            // if childNode is not null, it means the actual childNodes list is
            // longer than the virtual children list.
            if (!childrenMatch || childNode) {
              /* istanbul ignore if */
              if (process.env.NODE_ENV !== 'production' &&
                typeof console !== 'undefined' &&
                !hydrationBailed
              ) {
                hydrationBailed = true
                console.warn('Parent: ', elm)
                console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children)
              }
              return false
            }
          }
        }
      }
      if (isDef(data)) {
        let fullInvoke = false
        for (const key in data) {
          if (!isRenderedModule(key)) {
            fullInvoke = true
            invokeCreateHooks(vnode, insertedVnodeQueue)
            break
          }
        }
        if (!fullInvoke && data['class']) {
          // ensure collecting deps for deep class bindings for future updates
          traverse(data['class'])
        }
      }
    } else if (elm.data !== vnode.text) {
      elm.data = vnode.text
    }
    return true
  }

  function assertNodeMatch(node, vnode, inVPre) {
    if (isDef(vnode.tag)) {
      return vnode.tag.indexOf('vue-component') === 0 || (
        !isUnknownElement(vnode, inVPre) &&
        vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
      )
    } else {
      return node.nodeType === (vnode.isComment ? 8 : 3)
    }
  }

  // isUndef: value === null || value == undefined
  // isDef: value !== null && value !== undefeind
  return function patch(oldVnode, vnode, hydrating, removeOnly) {
    if (isUndef(vnode)) { //1.新的不存在，旧的存在，删除
      //组件删除
      if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
      return
    }

    //初始化补丁变量
    let isInitialPatch = false
    //保存了所有组件,在解析完所有的组件后，在根app模板会循环此数组然后一次调用组件的mounted方法
    const insertedVnodeQueue = []

    if (isUndef(oldVnode)) { //2.旧的不存在，新的存在，插入路线
      //oldVnode是在_update方法传递的vm.$el, 这个el如果是根组件，那么就是id = app模板，而自定义组件不提高el,只提高template,因此这里为undefined
      //所以自定义组件会走此路线
      isInitialPatch = true
      createElm(vnode, insertedVnodeQueue)
    } else { //3.新的存在，旧的存在（要么是更新阶段，要么是初始化阶段, 初始化时oldVnode的值的模板，不是空）
      //判断是不是真实的Dom
      const isRealElement = isDef(oldVnode.nodeType)
      if (!isRealElement && sameVnode(oldVnode, vnode)) { //更新阶段
        // 进行diff patch阶段
        patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly)
      } else { //初始化阶段
        //首次初始化
        if (isRealElement) {

          // 开启SSR服务器渲染
          if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
            oldVnode.removeAttribute(SSR_ATTR)
            hydrating = true
          }
          if (isTrue(hydrating)) {
            if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
              invokeInsertHook(vnode, insertedVnodeQueue, true)
              return oldVnode
            }
          }
          // 将旧vNode用一个空的vNode保存起来
          oldVnode = emptyNodeAt(oldVnode)
        }

        // 这里得到的是模板Domy元素
        // 在下面的createElm方法里面添加的属性
        const oldElm = oldVnode.elm
        // 得到父级模板
        const parentElm = nodeOps.parentNode(oldElm)

        // 创建真正的Dom, 调用方法后真正Dom保存在vnode.elm属性里面
        createElm(
          vnode,
          insertedVnodeQueue,
          //极端罕见的边缘情况:不插入，如果旧元素在a
          //离开过渡。只有在结合跃迁+时才会发生
          oldElm._leaveCb ? null : parentElm, //传递父节点，用于子节点插入父节点建立依赖关系, _leaveCb变量是过渡动画那里的
          nodeOps.nextSibling(oldElm) //得到兄弟节点，用于子节点插入父节点建立级别关系或者是替换节点时的级别关系
        )


        if (isDef(vnode.parent)) {
          let ancestor = vnode.parent
          const patchable = isPatchable(vnode)
          while (ancestor) {
            for (let i = 0; i < cbs.destroy.length; ++i) {
              cbs.destroy[i](ancestor)
            }
            ancestor.elm = vnode.elm
            if (patchable) {
              for (let i = 0; i < cbs.create.length; ++i) {
                cbs.create[i](emptyNode, ancestor)
              }
              // #6513
              // invoke insert hooks that may have been merged by create hooks.
              // e.g. for directives that uses the "inserted" hook.
              const insert = ancestor.data.hook.insert
              if (insert.merged) {
                // start at index 1 to avoid re-invoking component mounted hook
                for (let i = 1; i < insert.fns.length; i++) {
                  insert.fns[i]()
                }
              }
            } else {
              registerRef(ancestor)
            }
            ancestor = ancestor.parent
          }
        }

        // 首次初始化这里的条件为ture，然后删除id=app的模板
        if (isDef(parentElm)) {
          removeVnodes([oldVnode], 0, 0)
        } else if (isDef(oldVnode.tag)) {
          invokeDestroyHook(oldVnode)
        }
      }
    }

    /**
     * 调用钩子函数,首次初始化不存在钩子, 每解析完一个组件就会调用push到insertedVnodeQueue里面
     * vnode: 解析好的完整的组件vnode
     * insertedVnodeQueue: 插入队列
     * isInitialPatch: 组件为true, 普通Dom false
     * 组件逻辑：vnode.data.pendingInsert = insertedVnodeQueue， 最底层的组件insertedVnodeQueue是空数组
     */
    invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
    return vnode.elm
  }
}
